package net.keebook.webapp.bean;

import java.io.IOException;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import net.keebook.webapp.dao.UserDao;
import net.keebook.webapp.entity.User;
import net.keebook.webapp.model.SessionModel;
import net.keebook.webapp.util.Messages;


@ManagedBean
@RequestScoped
public class ListUsersBean {
	@Inject
	private UserDao userDao;
	private SessionModel sessionModel;
	
	@PostConstruct
	public void init() throws IOException {
		setSessionModel(SessionModel.getInstance(FacesContext.getCurrentInstance()));
		
		if (!getSessionModel().getAdmin())  {
			Logger.getLogger(this.getClass()).warn("Forbidden access to bean from userId="+getSessionModel().getUserId());
			FacesContext.getCurrentInstance().getExternalContext().redirect("403.xhtml");
			return;
		}
		
		HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
		String exposableId = request.getParameter("delete");
		if (exposableId != null && !"".equals(exposableId)) {
			if (!getSessionModel().getAdmin()) return;
			
			User user = getUserDao().get(exposableId);
			if (user != null) {
				getUserDao().delete(user);
				FacesContext.getCurrentInstance().getExternalContext().redirect("admin-listusers.xhtml?msg="+Messages.ITEM_DELETED);
				return;
			}
			FacesContext.getCurrentInstance().getExternalContext().redirect("admin-listusers.xhtml?msg="+Messages.ITEM_DELETE_FAILED);
		}
	}
	
	public List<User> getUsers() {
		return getUserDao().getListOfPasswordUsers();
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public SessionModel getSessionModel() {
		return sessionModel;
	}

	public void setSessionModel(SessionModel sessionModel) {
		this.sessionModel = sessionModel;
	}
}
